package com.example.airobotinterviewrecord.handler;

import com.example.common.utils.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public ResponseEntity<Map<String, Object>> handleValidationException(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            String field = error.getField();
            String message = error.getDefaultMessage();
            errors.put(field, message);
        }
        return createResponse(ResultCode.BAD_REQUEST, errors);
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        return createResponse(ResultCode.BAD_REQUEST, e.getMessage());
    }

    /**
     * 处理 404 异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNoHandlerFoundException(NoHandlerFoundException e) {
        return createResponse(ResultCode.NOT_FOUND, null);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
        return createResponse(ResultCode.ERROR, e.getMessage());
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        return createResponse(ResultCode.ERROR, "系统异常，请稍后重试");
    }

    /**
     * 创建响应对象
     * @param resultCode 结果码枚举
     * @param data 响应数据
     * @return 响应实体
     */
    private ResponseEntity<Map<String, Object>> createResponse(ResultCode resultCode, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", resultCode.getCode());
        response.put("message", resultCode.getMessage());
        response.put("data", data);
        return ResponseEntity.status(HttpStatus.valueOf(resultCode.getCode())).body(response);
    }

    /**
     * 创建响应对象，携带自定义消息
     * @param resultCode 结果码枚举
     * @param customMessage 自定义消息
     * @return 响应实体
     */
    private ResponseEntity<Map<String, Object>> createResponse(ResultCode resultCode, String customMessage) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", resultCode.getCode());
        response.put("message", customMessage);
        response.put("data", null);
        return ResponseEntity.status(HttpStatus.valueOf(resultCode.getCode())).body(response);
    }
}